// import React from 'react'
// import styles from './index.module.less'
// export default function Pull({ children }) {
//     const onTouchStart = (e) => {
//         console.log("触摸开始");
//     }
//     const onTouchMove = (e) => {
//         console.log("触摸移动");
//     }
//     const onTouchEnd = (e) => {
//         console.log("触摸结束");
//     }
//     return (
//         <div className={styles['pull-wrapper']}
//             onTouchStart={onTouchStart}
//             onTouchMove={onTouchMove}
//             onTouchEnd={onTouchEnd}
//         >
//             <div className={styles['pull-header']}>
//                 <p className={styles['pull-header-title']}>下拉刷新</p>
//             </div>
//             {children}
//         </div>
//     )
// }


import { useState, useRef, useCallback } from 'react';
import styles from './index.module.less';

const PullRefresh = ({ children, onRefresh, refreshThreshold = 60 }) => {
    const [pullDistance, setPullDistance] = useState(0);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [pullStatus, setPullStatus] = useState('pull'); // pull, release, refreshing

    const startY = useRef(0);
    const currentY = useRef(0);
    const isPulling = useRef(false);
    const wrapperRef = useRef(null);

    const onTouchStart = useCallback((e) => {
        // 只有在页面顶部时才允许下拉
        if (wrapperRef.current && wrapperRef.current.scrollTop === 0) {
            startY.current = e.touches[0].clientY;
            isPulling.current = true;
        }
    }, []);

    const onTouchMove = useCallback((e) => {
        if (!isPulling.current || isRefreshing) return;

        currentY.current = e.touches[0].clientY;
        const distance = currentY.current - startY.current;

        if (distance > 0) {
            // 阻止页面滚动
            // e.preventDefault();

            // 使用阻尼效果，让下拉距离递减
            const dampingDistance = distance * 0.5;
            setPullDistance(Math.min(dampingDistance, refreshThreshold * 1.5));

            // 更新状态
            if (dampingDistance >= refreshThreshold) {
                setPullStatus('release');
            } else {
                setPullStatus('pull');
            }
        }
    }, [refreshThreshold, isRefreshing]);

    const onTouchEnd = useCallback(async () => {
        if (!isPulling.current) return;

        isPulling.current = false;

        if (pullDistance >= refreshThreshold && !isRefreshing) {
            // 触发刷新
            setIsRefreshing(true);
            setPullStatus('refreshing');
            setPullDistance(refreshThreshold);

            try {
                if (onRefresh) {
                    await onRefresh();
                }
            } catch (error) {
                console.error('刷新失败:', error);
            } finally {
                // 刷新完成，回弹动画
                setTimeout(() => {
                    setIsRefreshing(false);
                    setPullStatus('pull');
                    setPullDistance(0);
                }, 500);
            }
        } else {
            // 回弹动画
            setPullDistance(0);
            setPullStatus('pull');
        }
    }, [pullDistance, refreshThreshold, isRefreshing, onRefresh]);

    // 获取状态文本
    const getStatusText = () => {
        switch (pullStatus) {
            case 'pull':
                return '下拉刷新';
            case 'release':
                return '释放刷新';
            case 'refreshing':
                return '刷新中...';
            default:
                return '下拉刷新';
        }
    };

    // 获取图标样式类
    const getIconClass = () => {
        let baseClass = styles['pull-icon'];
        if (pullStatus === 'refreshing') {
            baseClass += ` ${styles['pull-icon-refreshing']}`;
        } else if (pullStatus === 'release') {
            baseClass += ` ${styles['pull-icon-release']}`;
        }
        return baseClass;
    };

    // 动态样式
    const headerStyle = {
        transform: `translateY(${pullDistance}px)`,
        transition: isPulling.current ? 'none' : undefined,
    };

    const contentStyle = {
        transform: `translateY(${pullDistance}px)`,
        transition: isPulling.current ? 'none' : undefined,
    };

    return (
        <div
            ref={wrapperRef}
            className={styles['pull-wrapper']}
            onTouchStart={onTouchStart}
            onTouchMove={onTouchMove}
            onTouchEnd={onTouchEnd}
        >
            <div
                className={styles['pull-header']}
                style={headerStyle}
            >
                <div className={styles['pull-content']}>
                    <svg
                        className={getIconClass()}
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                    >
                        {pullStatus === 'refreshing' ? (
                            <path d="M21 12a9 9 0 11-6.219-8.56" />
                        ) : (
                            <path d="M12 19V5M5 12l7-7 7 7" />
                        )}
                    </svg>
                    <span className={styles['pull-text']}>{getStatusText()}</span>
                </div>
            </div>

            <div
                className={styles['content-wrapper']}
                style={contentStyle}
            >
                {children}
            </div>
        </div>
    );
};

export default PullRefresh;